package tools

import (
	"github.com/sirupsen/logrus"
	"log"
	"os"
	"time"
)

var Logger *logrus.Logger

func init() {
	src, err := setOutputFile()
	if err != nil {
		log.Fatalf("err: %v", err.Error())
	}
	if Logger == nil {
		Logger = logrus.New()
	}
	Logger.Out = src
	Logger.SetLevel(logrus.DebugLevel)
	Logger.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})
}

func setOutputFile() (*os.File, error) {
	now := time.Now()
	logFilePath := ""
	if dir, err := os.Getwd(); err == nil {
		logFilePath = dir + "./pet-system/logs/"
	}
	_, err := os.Stat(logFilePath)
	if os.IsNotExist(err) {
		if err = os.MkdirAll(logFilePath, 0777); err != nil {
			// 若创建失败，打印错误信息并退出程序
			log.Fatalf("err: %v", err.Error())
			return nil, err
		}
	}
	logFIleName := now.Format("2006-01-02") + ".log"
	fileName := logFilePath + logFIleName
	if _, err = os.Stat(fileName); err != nil {
		if _, err = os.Create(fileName); err != nil {
			log.Fatalf("err: %v", err.Error())
			return nil, err
		}
	}
	src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err != nil {
		log.Fatalf("err: %v", err.Error())
		return nil, err
	}
	return src, nil
}
